﻿// <copyright file="LoadCategoriesTree.cs" company="Auros Ltd.">
//     Copyright (c) Auros Ltd. All rights reserved.
// </copyright>

namespace Auros.Categorisation.Umbraco
{
    using System.Collections.Generic;
    using System.Linq;
    using Auros.Categorisation.Data;
    using umbraco.BusinessLogic.Actions;
    using umbraco.cms.presentation.Trees;
    using umbraco.interfaces;
    using System;
    using umbraco.businesslogic;

    /// <summary>
    /// Class represents the categories tree.
    /// </summary>
    [Tree("categories", "categories", "Categories")]
    public class LoadCategoriesTree : BaseTree
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="LoadCategoriesTree"/> class.
        /// </summary>
        /// <param name="application">The application.</param>
        public LoadCategoriesTree(string application)
            : base(application) 
        { 
        }

        /// <summary>
        /// Renders the JavaScipt.
        /// </summary>
        /// <param name="javascript">The JavaScript string builder.</param>
        public override void RenderJS(ref System.Text.StringBuilder javascript)
        {
            if (!String.IsNullOrEmpty(this.FunctionToCall))
            {
                javascript.Append("function OpenCategoryEdit(id) {\n");
                javascript.Append(this.FunctionToCall + "(id);\n");
                javascript.Append("}\n");
            }
            else if (!this.IsDialog)
            {
                javascript.Append(
                @"
                    function OpenCategoryEdit(id) 
                    { 
                        parent.right.document.location.href = '/umbraco/plugins/Categorisation/EditCategory.aspx?id=' + id; 
                    }
                ");
            }
        }

        /// <summary>
        /// Renders the specified tree.
        /// </summary>
        /// <param name="tree">The tree being generated.</param>
        public override void Render(ref XmlTree tree)
        {
            // If the current tree ID is the same as the root item ID, set category level to 0;
            int categoryLevelRoot = this.id == this.StartNodeID ? 0 : this.id;

            Category[] categories = Categories.GetAllCategories(categoryLevelRoot);

            foreach (var category in categories)
            {
                // Create a new node for the current category.
                XmlTreeNode node = XmlTreeNode.Create(this);

                node.NodeID = category.ID.ToString();

                if (StringHelpers.DictionaryItemExists(category.Name))
                    node.Text = String.Format("{0} ({1})", category.LocalizedName, category.Name);
                else
                    node.Text = category.Name;

                // Depending on the status of the current category, set the icon to appear within the tree.
                if (!category.Enabled)
                    node.Icon = "category_disabled.gif";
                else if (!category.Selectable)
                    node.Icon = "folder.gif";
                else
                    node.Icon = "category.gif";

                node.Action = "javascript:OpenCategoryEdit(" + category.ID.ToString() + ")";

                // Add context menu options.
                node.Menu.Clear();
                node.Menu.AddRange(new IAction[] 
                    { 
                        ActionNew.Instance, 
                        ActionDelete.Instance,
                        ActionCategoryMove.Instance,
                        ContextMenuSeperator.Instance,
                        ActionRefresh.Instance
                    });

                int numberOfChildren = category.Children.Count;

                if (numberOfChildren > 1)
                {
                    node.Menu.InsertRange(3, new IAction[] 
                    { 
                        ContextMenuSeperator.Instance, 
                        ActionCategorySort.Instance
                    });
                }

                // Check whether the current category has any children.
                if (numberOfChildren > 0)
                    node.Source = this.GetTreeServiceUrl(category.ID);

                tree.Add(node);
            }
        }

        /// <summary>
        /// Creates the root node.
        /// </summary>
        /// <param name="rootNode">The root node.</param>
        protected override void CreateRootNode(ref XmlTreeNode rootNode)
        {
            // Configure root node.
            rootNode.Icon = FolderIcon;
            rootNode.OpenIcon = FolderIconOpen;
            rootNode.NodeType = TreeAlias;
            rootNode.NodeID = "init";

            // Add context menu options.
            rootNode.Menu.Clear();
            rootNode.Menu.AddRange(new IAction[] 
            { 
                ActionNew.Instance,
                ContextMenuSeperator.Instance,
                ActionCategorySort.Instance,
                ContextMenuSeperator.Instance,
                ActionRefresh.Instance
            });
        }
    }
}